const request = require('../utils/request');
const { ProjectManage } = require('../model/enviromentModel');
const simpleGit = require('simple-git');
const config = require('../config');

module.exports = {
    async saveProject(data) {
        if(data.id) {
            //编辑
            return ProjectManage.update(data, {where: {id: data.id}});
        } else {
            //新建
            const SimpleGit = simpleGit({
                binary: 'git',
                maxConcurrentProcesses: 6,
                baseDir: `${config.localDir}`
            });
            const found = data.gitAddr.match((/(?<=:).*(?=\.)/))[0].split('/');
            data.owner = found[0];
            data.repo = found[1];
            if(!data.isRemoteMerge) {
                await SimpleGit
                .clone(data.gitAddr)
                .catch((error) => {
                    throw new Error(error);
                });
            }
            return ProjectManage.create(data);
        }
    },
    async findAllProject() {
        return ProjectManage.findAll();
    },
    async findAllProjectByCode(projects) {
        return ProjectManage.findAll({
            where: {
                id: projects && projects.map((p) => {
                    return p.id;
                })
            }
        })
    },
}